//
//  DDCouponViewController.m
//  Dingdong
//
//  Created by 程强 on 16/11/11.
//  Copyright © 2016年 程强. All rights reserved.
//

#import "DDCouponViewController.h"
#import "DDCouponTableCell.h"
#import "DDOrderManager.h"
#import "DDUserManager.h"
#import "MJRefresh.h"
#import "KSTabButtonView.h"

@interface DDCouponViewController ()<UITableViewDelegate,UITableViewDataSource,KSTabButtonViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *couponTable;
@property (weak, nonatomic) IBOutlet UIView *backView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topBackViewHeight;
@property (strong, nonatomic) DDOrderManager *manager;
@property (strong, nonatomic) DDCouponSet *couponSet;
@property (strong, nonatomic) SelectedCouponHandler couponHandler;
@property (strong, nonatomic) DDUserManager *userManager;
@property (assign, nonatomic) NSInteger currentPage;
@property (strong, nonatomic) DDMyCouponSet *mySet;
@end

@implementation DDCouponViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [DDOrderManager new];
    self.userManager = [DDUserManager new];
    [self layoutCouponView];
}
- (void)layoutCouponView
{
    if (self.couponType == DingDongShowCouponTypeStore) {
        self.backView.hidden = YES;
        self.topBackViewHeight.constant = 0;
        [self fetchStoreCoupon];
    }else{
        self.couponType = DingDongShowCouponTypeAll;
        [self setRefresh];
        KSTabButtonView *tapView = [[KSTabButtonView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
        tapView.items = @[@"All",@"Not Used",@"Used",@"Expired"];
        tapView.delegate = self;
        [self.backView addSubview:tapView];
    }
}
- (void)ksTabButtonView:(KSTabButtonView *)tabView didSelectIndex:(NSInteger)index
{
    switch (index) {
        case 0:
            self.couponType = DingDongShowCouponTypeAll;
            break;
        case 1:
            self.couponType = DingDongShowCouponTypeUnUse;
            break;
        case 2:
            self.couponType = DingDongShowCouponTypeUsed;
            break;
        case 3:
            self.couponType = DingDongShowCouponTypeOverdue;
            break;
        default:
            break;
    }
    
    [self headerRefresh];
}
- (void)setRefresh
{
    MJRefreshHeader *header =[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self headerRefresh];
    }];
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self footerRefresh];
    }];
    [self.couponTable setMj_header:header];
    [self.couponTable setMj_footer:footer];
    [self headerRefresh];
}
- (void)headerRefresh
{
    weak_Self(self);
    [self fetchCouponByType:self.couponType pull:YES complete:^{
        [weakSelf.couponTable.mj_header endRefreshing];
    }];
}
- (void)footerRefresh
{
    weak_Self(self);
    [self fetchCouponByType:self.couponType pull:YES complete:^{
        [weakSelf.couponTable.mj_footer endRefreshing];
    }];
}
#pragma mark --- 获取店铺可用的优惠券
- (void)fetchStoreCoupon
{
    weak_Self(self);
    NSNumber *store_id = self.storeInfo[@"store_id"];
    NSNumber *store_price = self.storeInfo[@"store_price"];
    [[self.manager getCoupons:store_id storeprice:[store_price stringValue]]subscribeNext:^(id x) {
        weakSelf.couponSet = x;
        [weakSelf.couponTable reloadData];
        if (weakSelf.couponSet.couponAry.count == 0) {
            [weakSelf showNoContentViewWithOriginY:65 image:@"no_jifen" message:@"No Coupon"];
        }else{
            [weakSelf hideNoContentView];
        }
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)fetchCouponByType:(DingDongShowCouponType)type pull:(BOOL)pull complete:(void(^)())block
{
    weak_Self(self);
    if (pull) {
        self.currentPage = 1;
    }
    [self showHUD];
    [[self.userManager getCouponListByType:type page:self.currentPage size:kPageSize]subscribeNext:^(id x) {
        if (pull) {
            [weakSelf.mySet.couponAry removeAllObjects];
            weakSelf.mySet = x;
        }else{
            DDMyCouponSet *Set = x;
            [weakSelf.mySet.couponAry addObjectsFromArray:Set.couponAry];
        }
        if (weakSelf.mySet.couponAry.count == 0) {
            [weakSelf showNoContentViewWithOriginY:115 image:@"no_jifen" message:@"No Coupon"];
        }else{
            [weakSelf hideNoContentView];
        }
        [weakSelf.couponTable reloadData];
        weakSelf.currentPage+=1;
    } error:^(NSError *error) {
        
    } completed:^{
        if (block) {
            block();
        }
        [weakSelf hideHUD];
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.couponType == DingDongShowCouponTypeStore) {
        return self.couponSet.couponAry.count;
    }else{
        return self.mySet.couponAry.count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.couponType == DingDongShowCouponTypeStore) {
        return 120.0;
    }
    return 130.0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.couponType == DingDongShowCouponTypeStore){
        static NSString *indentifier = @"SelectCouponCell";
        DDCouponSelectTableCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
        if (!cell) {
            cell = [[DDCouponSelectTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        DDCouponObj *coupon = self.couponSet.couponAry[indexPath.row];
        cell.couponMoneyLbl.text = FormatString(@"$%@", coupon.type_money);
        cell.couponNameLbl.text = coupon.type_name;
        cell.couponDesLbl.text = FormatString(@"Full $%@ minus $%@", coupon.min_goods_amount,coupon.type_money);
        NSString *start = [ToolKit timeStampTurnDate:[coupon.use_start_date stringValue] withFormat:@"yyyy.MM.dd"];
        NSString *end = [ToolKit timeStampTurnDate:[coupon.use_end_date stringValue] withFormat:@"yyyy.MM.dd"];
        cell.validTimeLbl.text = FormatString(@"Validity:%@-%@", start,end);
        return cell;
    }else{
        static NSString *indentifier = @"CouponCell";
        
        DDCouponTableCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
        
        if (!cell) {
            cell = [[DDCouponTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
        }
        DDCouponObj *coupon = self.mySet.couponAry[indexPath.row];
        cell.moneyLbl.text = FormatString(@"$%@", coupon.type_money);
        cell.shopNameLbl.text = coupon.store_name;
        cell.desLbl.text = FormatString(@"Full%@minus%@", coupon.min_goods_amount,coupon.type_money);
        NSString *start = [ToolKit timeStampTurnDate:[coupon.use_start_date stringValue] withFormat:@"yyyy.MM.dd"];
        NSString *end = [ToolKit timeStampTurnDate:[coupon.use_end_date stringValue] withFormat:@"yyyy.MM.dd"];
        cell.dateLbl.text = FormatString(@"Validity:%@-%@", start,end);
        
        return cell;

    }
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.couponType == DingDongShowCouponTypeStore) {
        DDCouponSelectTableCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.couponSelectBtn.selected = YES;
        DDCouponObj *coupon = self.couponSet.couponAry[indexPath.row];
        if (self.couponHandler) {
            self.couponHandler(coupon);
        }
        [self gotoBack];
    }
}
- (void)userSelectCouponHandler:(SelectedCouponHandler)handler
{
    self.couponHandler = handler;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
